<?php
/**
 * @category Goatherd
 * @package Goatherd
 *
 * @author Copyright (c) 2012 Maik Penz <maik@phpkuh.de>
 * @version $Id: SubjectTrait.php 93 2012-04-25 20:53:56Z maik@phpkuh.de $
 *
 * This file is part of Goatherd library.
 *
 * Goatherd library is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Goatherd library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Goatherd library. If not, see <http://www.gnu.org/licenses/>.
 */
namespace Goatherd\Commons\Observer;

/**
 * Basic subject implementation.
 *
 * @category Goatherd
 * @package Goatherd
 * @subpackage Commons
 */
trait SubjectTrait
{
    /**
     *
     * @var array
     */
    private $_subjectObservers = array();

    /**
     *
     * @var string
     */
    private $_subjectEventName = '';

    /**
     *
     * @var mixed
     */
    private $_subjectEventData = null;

    /**
     *
     * @var boolean
     */
    private $_subjectEventLoop = false;

    /**
     *
     * @param \SplObserver $observer
     */
    public function attach(\SplObserver $observer)
    {
        $key = spl_object_hash($observer);
        $this->_subjectObservers[$key] = $observer;

        return $this;
    }

    /**
     *
     * @param \SplObserver $observer
     */
    public function detach(\SplObserver $observer)
    {
        $key = spl_object_hash($observer);
        if (array_key_exists($key, $this->_subjectObservers)) {
            unset($this->_subjectObservers[$key]);
        }

        return $this;
    }

    /**
     *
     */
    public function notify ()
    {
        if ($this->_subjectEventLoop) {
            throw new \Exception('Notify loop detected.');
        }

        // notify loop
        $this->_subjectEventLoop = true;
        foreach ($this->_subjectObservers as $observer) {
            $observer->update($this);
        }
        $this->_subjectEventLoop = false;

        return $this;
    }

    /**
     *
     * @return null
     */
    public function getEventData()
    {
        return $this->_subjectEventData;
    }

    /**
     *
     * @param mixed $data
     */
    public function setEventData($data)
    {
        $this->_subjectEventData = $data;

        return $this;
    }

    /**
     *
     * @return string
     */
    public function getEventName()
    {
        return $this->_subjectEventName;
    }

    /**
     *
     * @param string $name
     */
    public function setEventName($name)
    {
        $this->_subjectEventName = '' . $name;

        return $this;
     }
}